package com.phenix.mvp.aop.aspect;

import com.orhanobut.logger.Logger;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;

import java.util.concurrent.TimeUnit;

/**
 * Created by zhouphenix on 2016-12-25.
 * 根据注解TimeLog自动添加打印方法耗代码，通过aop切片的方式在编译期间织入源代码中
 * 功能：自动打印方法的耗时
 */
@Aspect
public class TimeLogAspect {

    @Pointcut("execution(@com.phenix.annotation.aspect.TimeLog * *(..))")//方法切入点
    public void methodAnnotated(){}

    @Pointcut("execution(@com.phenix.annotation.aspect.TimeLog *.new(..))")//构造器切入点
    public void constructorAnnotated(){}


    @Around("methodAnnotated() || constructorAnnotated()")//在连接点进行方法替换
    public Object aroundJoinPoint(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        String className = methodSignature.getDeclaringType().getSimpleName();
        String methodName = methodSignature.getName();
        long startTime = System.nanoTime();
        Object result = joinPoint.proceed();//执行原方法
        StringBuilder sb = new StringBuilder(methodName);
        for (Object o: joinPoint.getArgs() ) {
            if (o instanceof String) sb.append(o.toString());
            else if(o instanceof Class) sb.append(((Class)o).getSimpleName());

        }
        Logger.t("TimeLog").d(className + "." + sb.toString() + joinPoint.getArgs().toString() + "--->"
                + "[" + TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime) + "ms" + "]");
        return result;
    }
}
